<template>
	<v-dialog v-model="visible" width="800px">
		<v-card>
			<v-card-text>
				<div class="pt-5">{{ modText }}用户</div>
			</v-card-text>
			<v-card-text>
				<v-form @submit.prevent.stop.capture ref="form">
					<v-text-field label="用户昵称" v-model="form.username" :rules="rules.username"/>
					<v-text-field label="邮箱" type="email" v-model="form.email" :rules="rules.email"/>
					<v-text-field label="密码" type="password" v-model="form.password" :rules="rules.password"/>
				</v-form>
			</v-card-text>
			<v-card-actions class="justify-end">
				<v-btn @click="visible = false">取消</v-btn>
				<v-btn color="success" :loading="confirmLoading" @click="onSave">确认</v-btn>
			</v-card-actions>
		</v-card>
	</v-dialog>
</template>

<script>
import MdDialogMixins from '@/common/mixins/MdDialogMixins';
import UserApi from '@/common/api/UserApi';

export default {
	name: 'UserDialog',
	mixins: [MdDialogMixins],
	data() {
		return {
			oldUser: {},
			rules: {
				username: this.$utils.formValidator(['required', 'string', 'max:64', 'min:2']),
				email: this.$utils.formValidator(['required', 'string', 'email', 'max:64', 'min:2']),
				password: this.$utils.formValidator(['required', 'string', 'max:64', 'min:6'])
			}
		}
	},
	methods: {
		onSave() {
			if (!this.$refs.form.validate()) {
				return;
			}
			this.confirmLoading = true;
			if (this.form.id) {
				let data = this.$utils.objectSubtraction(this.form, this.oldUser);
				if (Object.keys(data).length === 0) {
					this.$emit('success');
					this.visible = false;
					return;
				}
				UserApi.admin.update(this.form.id, data).then(res => {
					this.$utils.responseHandler(res).then(() => {
						this.$emit('success');
						this.visible = false;
					})
				}).finally(() => this.confirmLoading = false)
			} else {
				UserApi.create(this.form).then(res => {
					this.$utils.responseHandler(res).then(() => {
						this.$emit('success');
						this.visible = false;
					})
				}).finally(() => this.confirmLoading = false)
			}
		},
		add() {
			this.action({}, 'add')
			this.rules.password = this.$utils.formValidator(['required', 'string', 'max:64', 'min:6'])
		},
		edit(data) {
			this.oldUser = this.$utils.deepCopy(data);
			this.rules.password = this.$utils.formValidator(['nullable', 'string', 'max:64', 'min:6'])
			this.action(data, 'add')
		}
	}
}
</script>

<style scoped>

</style>